<?php
/**
 * 夏日葵电商系统
 * http://www.xiarikui.com
 */
namespace Home\Controller;
use Think\Controller;
class BaseController extends Controller {
    public $user = array();
    public $user_id = 0;
    public $session_id;
    public $weixin_config;
    public $cateTree = array();
    /*
     * 初始化操作
     */
    public function __construct() {
		parent::__construct();
		//获取微信配置
        $wechat_list = M('wx_user')->select();
        //微信浏览器
        if (strstr($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') && $wechat_list[0]['wait_access']) {
            $wechat_config = $wechat_list[0];
            $this->weixin_config = $wechat_config;
            $this->assign('wechat_config', $wechat_config); // 微信配置
			if ($wechat_config && !$_SESSION['openid']) {
                //去授权获取openid
                $wxuser = $this->GetOpenid();
                //获取用户昵称
                session('subscribe', $wxuser['subscribe']); // 当前这个用户是否关注了微信公众号
                //微信自动登录
				$mod = M('users');
				$check = $mod->where(array('openid'=>$wxuser['openid']))->getField('id');  
				if($check){
					$mod->where(array('openid'=>$wxuser['openid']))->save(array('user_name'=>trim($wxuser['nickname']),'head_picture'=>$wxuser['headimgurl'],'sex'=>$wxuser['sex']));
				}else{
					$result = $mod->add(array('openid'=>$wxuser['openid'],'user_name'=>trim($wxuser['nickname']),'head_picture'=>$wxuser['headimgurl'],'sex'=>$wxuser['sex'],'add_time'=>time()));
				}   
				session('user_id',$check['id']?$check['id']:$result); 
            }
        }
    }
    /**
     * 保存公告变量到 smarty中 比如 导航 
     */
    public function publicAssign() {
        $xiarikui_config = array();
        $xrk_config = M('config')->cache(true, XIARIKUI_CACHE_TIME)->select();
        foreach ($xrk_config as $k => $v) {
            if ($v['name'] == 'hot_keywords') {
                $xiarikui_config['hot_keywords'] = explode('|', $v['value']);
            }
            $xiarikui_config[$v['inc_type'] . '_' . $v['name']] = $v['value'];
        }
        $goods_cat_tree = get_goods_cat_tree();
        $this->cateTree = $goods_cat_tree;
        $this->assign('goods_cat_tree', $goods_cat_tree);
        $brand_list = M('brand')->cache(true, XIARIKUI_CACHE_TIME)->field('id,parent_cat_id,logo,is_hot')->where("parent_cat_id>0")->select();
        $this->assign('brand_list', $brand_list);
        $this->assign('xiarikui_config', $xiarikui_config);
    }
    // 网页授权登录获取 OpendId
    public function GetOpenid() {
        if ($_SESSION['openid'])
            return array('openid'=>$_SESSION['openid']);
        //通过code获得openid
        if (!isset($_GET['code'])) {
            //触发微信返回code码
            //$baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']);
            $baseUrl = urlencode($this->get_url());
            $url = $this->__CreateOauthUrlForCode($baseUrl); // 获取 code地址
            Header("Location: $url"); // 跳转到微信授权页面 需要用户确认登录的页面
            exit();
        } else {
            // 上面跳转, 这里跳了回来
            //获取code码，以获取openid
            $code = $_GET['code'];
            $data = $this->getOpenidFromMp($code);
            $data2 = $this->GetUserInfo($data['access_token'], $data['openid']);
            $data['nickname'] = $data2['nickname'];
            $data['sex'] = $data2['sex'];
            $data['headimgurl'] = $data2['headimgurl'];
            $data['subscribe'] = $data2['subscribe'];
            $_SESSION['openid'] = $data['openid'];
            return $data;
        }
    }
    /**
     * 获取当前的url 地址
     * @return type
     */
    private function get_url() {
        $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
        $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
        $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
        $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
        return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;
    }
    /**
     *
     * 通过code从工作平台获取openid机器access_token
     * @param string $code 微信跳转回来带上的code
     *
     * @return openid
     */
    public function GetOpenidFromMp($code) {
        //通过code换取网页授权access_token  和 openid
        $url = $this->__CreateOauthUrlForOpenid($code);
        $ch = curl_init(); //初始化curl        
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置超时
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $res = curl_exec($ch); //运行curl，结果以jason形式返回            
        $data = json_decode($res, true); //取出openid access_token                
        curl_close($ch);
        return $data;
    }
    /**
     *
     * 通过access_token openid 从工作平台获取UserInfo      
     * @return openid
     */
    public function GetUserInfo($access_token, $openid) {
        // 获取用户 信息
        $url = $this->__CreateOauthUrlForUserinfo($access_token, $openid);
        $ch = curl_init(); //初始化curl        
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置超时
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $res = curl_exec($ch); //运行curl，结果以jason形式返回            
        $data = json_decode($res, true); //取出openid access_token                
        curl_close($ch);
        // 获取看看用户是否关注了 你的微信公众号， 再来判断是否提示用户 关注
        $access_token2 = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token2&openid=$openid";
        $subscribe_info = httpRequest($url, 'GET');
        $subscribe_info = json_decode($subscribe_info, true);
        $data['subscribe'] = $subscribe_info['subscribe'];
        return $data;
    }
    public function getAccessToken() {
        //判断是否过了缓存期
        $wechat = M('wx_user')->find();
        $expire_time = $wechat['web_expires'];
        if ($expire_time > time()) {
            return $wechat['web_access_token'];
        }
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$wechat[appid]}&secret={$wechat[appsecret]}";
        $return = httpRequest($url, 'GET');
        $return = json_decode($return, 1);
        $web_expires = time() + 7000; // 提前200秒过期
        M('wx_user')->where(array('id' => $wechat['id']))->save(array('web_access_token' => $return['access_token'], 'web_expires' => $web_expires));
        return $return['access_token'];
    }
    /**
     *
     * 构造获取code的url连接
     * @param string $redirectUrl 微信服务器回跳的url，需要url编码
     *
     * @return 返回构造好的url
     */
    private function __CreateOauthUrlForCode($redirectUrl) {
        $urlObj["appid"] = $this->weixin_config['appid'];
        $urlObj["redirect_uri"] = "$redirectUrl";
        $urlObj["response_type"] = "code";
//        $urlObj["scope"] = "snsapi_base";
        $urlObj["scope"] = "snsapi_userinfo";
        $urlObj["state"] = "STATE" . "#wechat_redirect";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?" . $bizString;
    }
    /**
     *
     * 构造获取open和access_toke的url地址
     * @param string $code，微信跳转带回的code
     *
     * @return 请求的url
     */
    private function __CreateOauthUrlForOpenid($code) {
        $urlObj["appid"] = $this->weixin_config['appid'];
        $urlObj["secret"] = $this->weixin_config['appsecret'];
        $urlObj["code"] = $code;
        $urlObj["grant_type"] = "authorization_code";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://api.weixin.qq.com/sns/oauth2/access_token?" . $bizString;
    }
    /**
     *
     * 构造获取拉取用户信息(需scope为 snsapi_userinfo)的url地址     
     * @return 请求的url
     */
    private function __CreateOauthUrlForUserinfo($access_token, $openid) {
        $urlObj["access_token"] = $access_token;
        $urlObj["openid"] = $openid;
        $urlObj["lang"] = 'zh_CN';
        $bizString = $this->ToUrlParams($urlObj);
        return "https://api.weixin.qq.com/sns/userinfo?" . $bizString;
    }
    /**
     *
     * 拼接签名字符串
     * @param array $urlObj
     *
     * @return 返回已经拼接好的字符串
     */
    private function ToUrlParams($urlObj) {
        $buff = "";
        foreach ($urlObj as $k => $v) {
            if ($k != "sign") {
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        return $buff;
    }
    //更新购物车价格
    public function changeCartPrice(){
        $mod = M('cart');
        $time = time();
        $goods_mod = M('goods_store_spec');
        $user_id = session('user_id');
        $cart_list = $mod->where(array('user_id'=>$user_id))->select();
        foreach((array)$cart_list as $k=>$v) {
            $goods = $goods_mod->where(array('store_id' => $v['store_id'], 'goods_id' => $v['goods_id'], 'id' => $v['spec_id']))->field('spec_price,status,is_sold')->find();
            if($goods['is_sold']==1){
                $mod->where(array('id'=>$v['id']))->delete();
            }else if($goods['status']<1){
                $mod->where(array('id'=>$v['id']))->delete();
            }
            if ($v['pro_id'] > 0) {
                $info = M('goods_promotion')->where(array('id'=>$v['pro_id'],'start_time'=>array('elt',$time),'end_time'=>array('egt',$time)))->field('id,mall_number,use_number,use_price')->find();
                if(!$info['id']){
                    $mod->where(array('id'=>$v['id']))->save(array('pro_id'=>0,'pro_type'=>0,'goods_price'=>$goods['spec_price']));
                }
                if($v['pro_type']==3){
                    if($info['use_number']==$info['mall_number']){
                        $mod->where(array('id'=>$v['id']))->save(array('pro_id'=>0,'pro_type'=>0,'goods_price'=>$goods['spec_price']));
                    }
                }
            }else{
                if($goods['spec_price'] && $goods['spec_price']!=$v['goods_price']){
                    $mod->where(array('id'=>$v['id']))->save(array('goods_price'=>$goods['spec_price']));
                }
            }
        }
    }
    function check_pro_goods($info){
        //判断是否是促销商品
        $info['pro_id'] = 0;
        $info['pro_type'] = 0;
        $pro_mod = M('goods_promotion');
        $pro_info = $pro_mod->where('find_in_set('.$info['id'].',goods_list)')->find();
        if($pro_info['id']){
            if ($pro_info['type'] == 1) {
                $info['pro_id'] = $pro_info['id'];
                $info['pro_type'] = $pro_info['type_id'];
            }else{
                if($pro_info['spec_id']==$info['spec_id']) {
                    $info['pro_id'] = $pro_info['id'];
                    $info['pro_type'] = $pro_info['type_id'];
                }
            }
        }
    }
    function check_pro_price($cart_id){
        $mod = M('cart');
        $user_id = session('user_id');
        //判断是否有促销活动
        $pro_all_id = $mod->where(array('user_id'=>$user_id,'id'=>array('in',$cart_id),'pro_id'=>array('gt',0)))->group('pro_id')->field('pro_id,pro_type,goods_price,goods_number')->select();
        $pro_mod = M('goods_promotion');
        $pro_price = 0;
        foreach((array)$pro_all_id as $k=>$v){
            if($v['pro_type']==1) {
                $p_price = $mod->where(array('user_id' => $user_id, 'id' => array('in', $cart_id), 'pro_type' => 1))->sum('goods_price*goods_number');
                $pro_price += $pro_mod->where(array('fill_price' => array('elt', $p_price),'type_id'=>1))->order('use_price desc')->getField('use_price');
            }else{
                $pro_info = $pro_mod->where(array('id'=>$v['pro_id']))->field('use_price,use_number')->find();
                if($pro_info['use_number']>=$v['goods_number']) {
                    $pro_price += ($v['goods_price'] - $pro_info['use_price'])*$v['goods_number'];
                }else{
                    $pro_price += ($v['goods_price'] - $pro_info['use_price'])*$pro_info['use_number'];
                }
            }
        }
        $this->assign('pro_price',number_format($pro_price,2));
        return $pro_price;
    }
    //判读订单是否已取消
    function check_order_status(){
        $user_id = session('user_id');
        if($user_id){
            $mod = M('orders');
            $order_list = $mod->where(array('user_id'=>$user_id))->field('order_sn,status,add_time')->select();
            if($order_list['status']==1) {
                $time = time();
                foreach ((array)$order_list as $k => $v) {
                    if ($v['add_time'] + 600 < $time) {
                        $mod->where(array('order_sn' => $v['order_sn']))->save(array('status' => 4));
                    }
                }
            }
        }
    }
    //订单支付成功
    function success_pay_order($order_sn){
		if(!is_numeric($order_sn)){
			$mod = M('users_log');
			$user_id = session('user_id');
			$info = $mod->where(array('order_sn'=>$order_sn,'user_id'=>$user_id))->find();
			if($info['status']<1){
				$users_mod = M('users');
				$mod->where(array('id'=>$info['id']))->save(array('status'=>1));
				$user_price = $users_mod->where(array('id'=>$user_id))->getField('price');
				$users_mod->where(array('id'=>$user_id))->save(array('price'=>$user_price+$info['price']));
			}
		}else{
			$mod = M('orders');
			$g_mod = M('goods');
			$user_mod = M('users');
			$spec_mod = M('goods_store_spec');
			$pro_mod = M('goods_promotion');
			$goods_mod = M('orders_goods');
			$users_log_mod = M('users_log');
			$info = $mod->where(array('order_sn'=>$order_sn))->field('id,order_sn,status,user_id,order_price,pay_type,status')->order('id asc')->find();
			if($info['status']==1){
				$order_id = $info['id'];
				$goods_list = $goods_mod->where(array('order_sn'=>$info['order_sn']))->field('goods_id,spec_id,pro_type,pro_id,store_id')->select();
				$give_integral = 0;
				foreach((array)$goods_list as $k=>$v){
					$give_integral+= $g_mod->where('id='.$v['goods_id'])->getField('give_integral');
					if($v['pro_type']==3){
						$pro_mod->where(array('id'=>$v['pro_id']))->setInc('mall_number');
					}
					$spec_mod->where(array('spec_id'=>$v['spec_id']))->setInc('sale_number');
				}
				if($order_id){
					$this->order_log($info['order_sn'],'待发货','支付成功，商家拣货中');
					$user_name = M('users')->where(array('id'=>$info['user_id']))->getField('user_name');
					orders_status($user_name,$info['order_sn'],2,0,'');
					$result = $mod->where(array('order_sn'=>$info['order_sn']))->save(array('status'=>2,'pay_time'=>time()));
				}
			}
		}
    }
    //订单状态log
    function order_log($order_sn,$title,$contents){
        $mod = M('orders_log');
        $mod->add(array(
            'order_sn'=>$order_sn,
            'title'=>$title,
            'contents'=>$contents,
            'add_time'=>time()
        ));
    }
	
}
